package com.eden.manage.service;

import com.eden.manage.dto.PageComDto;
import com.eden.manage.dto.UserInfoDto;
import com.eden.manage.dto.member.MemberProfitDto;
import com.eden.manage.mapper.EdenMemberProfitParamMapper;
import com.eden.manage.model.EdenMemberProfitParam;
import com.eden.manage.req.query.MemberProfitQuery;
import com.eden.manage.utils.WebUserUtils;
import com.eden.manage.utils.mapstruct.PlatStructUtils;
import eden.api.common.enums.UserTypeEnum;
import eden.api.common.model.PageQuery;
import eden.api.common.utils.ErrorEnums;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class MemberProfitService {

    private final EdenMemberProfitParamMapper memberProfitParamMapper;

    public PageComDto<MemberProfitDto> pageList(MemberProfitQuery profitQuery){
        dealAuth(profitQuery);
        PageComDto<MemberProfitDto> pageDto = new PageComDto<>();
        int count = memberProfitParamMapper.countByPage(profitQuery);
        if(count > 0){
            List<MemberProfitDto> profitDtos = memberProfitParamMapper.selectPageList(profitQuery);
            pageDto.setList(profitDtos);
        }
        pageDto.setCount(count);
        return pageDto;
    }

    private void dealAuth(PageQuery profitQuery) {
        UserInfoDto userInfo = WebUserUtils.getUserInfo();
        if(userInfo.getType().equals(UserTypeEnum.PLAT.getCode())){
            String sb = "plat_id=" +
                    userInfo.getPlatId();
            profitQuery.setDataAuth(sb);
        }else if(userInfo.getType().equals(UserTypeEnum.AGENT.getCode())){
            String sb = "plat_id=" +
                    userInfo.getPlatId()  +" and agent_id=" + userInfo.getAgentId();
            profitQuery.setDataAuth(sb);
        }


    }

    @Transactional(rollbackFor = Exception.class)
    public void saveProfitParam(MemberProfitDto profitDto){
        UserInfoDto userInfo = WebUserUtils.getUserInfo();
        if(userInfo.getType().equals(UserTypeEnum.ADMIN.getCode())){
            throw new IllegalArgumentException(ErrorEnums.ADMIN_NOT_OPT.name());
        }
        if(userInfo.getType().equals(UserTypeEnum.PLAT.getCode())){
            throw new IllegalArgumentException(ErrorEnums.PLAT_NOT_OPT.name());
        }
        EdenMemberProfitParam profitParam = PlatStructUtils.INSTANCE.convertMemberParamDtoToDB(profitDto);
        if(profitDto.getId() == null || profitDto.getId() <= 0){
            profitParam.setPlatId(userInfo.getPlatId());
            profitParam.setAgentId(userInfo.getAgentId());
            memberProfitParamMapper.insert(profitParam);
        }else{
            memberProfitParamMapper.updateParam(profitDto);
        }

    }

}
